<template>
  <div style="display: inline-block" @click.stop>
    <el-popover
      v-model:visible="visible"
      :placement="placement"
      :width="150"
      popper-class="popover-search"
      trigger="click"
      @show="handleShow"
    >
      <template #reference>
        <span class="icon-wrap">
          <el-icon><el-icon-search /></el-icon>
        </span>
      </template>
      <div>
        <el-input ref="refInput" v-model="modelValue" @keyup.enter="handleSearch"></el-input>
        <div class="split-line">
          <el-link class="filter-button" :underline="false" :disabled="modelValue === ''" @click="handleSearch"
            >搜索</el-link
          >
          <el-link class="filter-button" :underline="false" @click="handleSearchReset">重置</el-link>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import { withDefaults, ref, computed } from 'vue'
import { ElPopover, ElInput, ElLink } from 'element-plus'
import type { Placement } from 'element-plus'
import { Search as ElIconSearch } from '@element-plus/icons-vue'

interface Props {
  prop: string
  value?: string
  placement?: Placement
}

// 定义属性
const props = withDefaults(defineProps<Props>(), {
  value: '',
  placement: 'bottom' as Placement
})

// 定义emit事件
const emits = defineEmits(['search', 'update:value'])

const refInput = ref()

const visible = ref(false)

const modelValue = computed({
  get: () => props.value,
  set: val => emits('update:value', val)
})

const handleSearch = () => {
  visible.value = false
  emits('search', { prop: props.prop })
}
const handleSearchReset = () => {
  visible.value = false
  modelValue.value = ''
  emits('search', { prop: props.prop })
}

const handleShow = () => {
  setTimeout(() => {
    refInput.value.focus()
  }, 0)
}
</script>

<style lang="scss" scoped>
.filter-button {
  background: transparent;
  border: none;
  color: #606266;
  cursor: pointer;
  font-size: 13px;
  padding: 0 3px;
  min-height: 18px;
  &[disabled] {
    color: #c0c4cc;
    cursor: not-allowed;
  }
  &:hover {
    color: $--color-text-link;
  }
  &[disabled]:hover {
    color: #c0c4cc;
  }

  & + .filter-button {
    margin-left: 3px;
  }
}
.split-line {
  border-top: 1px solid #ebeef5;
  padding: 8px 8px 0 0;
}
:deep(.el-link) {
  &.el-link--inner:hover {
    text-decoration: none !important;
  }
}
.icon-wrap {
  display: -webkit-inline-box;
  display: -ms-inline-flexbox;
  display: inline-flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  -webkit-box-align: flex-end;
  -ms-flex-align: flex-end;
  align-items: flex-end;
  height: 14px;
  width: 20px;
  vertical-align: middle;
  cursor: pointer;
  overflow: initial;
  position: relative;
  i {
    color: $--color-text-placeholder;
  }
}
</style>
